package com.suncky.frame.utils;

import android.util.SparseArray;

/**
 * 防止重复点击
 * @author gl
 * @time 2021/9/24 15:24
 */
public class SingleClickManager {

    private SingleClickManager() {
    }

    private static final SingleClickManager instance = new SingleClickManager();

    private int clickInterval = 1000;//ms
    private final SparseArray<Long> lastClickTimes = new SparseArray<>();//上次点时间

    public synchronized static SingleClickManager getInstance(){
        return instance;
    }

    /**
     * 设置检验点击时间间隔
     * @param interval 间隔时间(毫秒) 默认1000ms,传0时不校验重复点击
     */
    public static void clickInterval(int interval) {
        getInstance().setClickInterval(interval);
    }

    public void setClickInterval(int interval) {
        clickInterval = interval;
    }

    private boolean getIsReClick(int viewId,int interval) {
        long currTime = System.currentTimeMillis();
        Long lastTime = lastClickTimes.get(viewId);
        if (lastTime == null) {
            lastTime = 0L;
        }
        boolean reClick = currTime - lastTime <= interval;
        if (!reClick) {
            lastClickTimes.put(viewId,currTime);
        }else {
            LogUtils.i("ReClick within "+interval+"ms");
        }
        return reClick;
    }


    /**
     * 是否是重复点击
     * @return 重复点击true  否则false
     */
    public static boolean isReClick() {
        return getInstance().getIsReClick(0,getInstance().clickInterval);
    }

    /**
     * 是否是重复点击
     * @param viewId 点击的view id, 为0时不区分view
     * @return 重复点击true  否则false
     */
    public static boolean isReClick(int viewId) {
        return getInstance().getIsReClick(viewId, getInstance().clickInterval);
    }

    /**
     * 是否是重复点击
     * @param viewId 点击的view id, 为0时不区分view
     * @param interval 点击间隔(毫秒)
     * @return 重复点击true  否则false
     */
    public static boolean isReClick(int viewId,int interval) {
        return getInstance().getIsReClick(viewId, interval);
    }
}
